package com.middlegroup.common.utils;

import com.middlegroup.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;


/**
 * 前后端数据传输加密工具类
 *
 * @author pc
 */
@Slf4j
public class AesUtils {
 
    //参数分别代表 算法名称/加密模式/数据填充方式
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
 
    /**
     * 加密
     * @param content 加密的字符串
     * @param encryptKey key值
     * @return
     * @throws Exception
     */
    public static String encrypt(String content, String encryptKey)  {
        byte[] b = null;
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128);
            Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
            b = cipher.doFinal(content.getBytes("utf-8"));
        }catch (InvalidKeyException e){
            log.error("AES加密异常",e);
            throw new BusinessException(e.getMessage());
        }catch (NoSuchAlgorithmException e){
            log.error("AES加密异常",e);
            throw new BusinessException(e.getMessage());
        }catch (NoSuchPaddingException e){
            log.error("AES加密异常",e);
            throw new BusinessException(e.getMessage());
        }catch (UnsupportedEncodingException e){
            log.error("AES加密异常",e);
            throw new BusinessException(e.getMessage());
        }catch (BadPaddingException e){
            log.error("AES加密异常",e);
            throw new BusinessException(e.getMessage());
        }catch (IllegalBlockSizeException e){
            log.error("AES加密异常",e);
            throw new BusinessException(e.getMessage());
        }
        // 采用base64算法进行转码,避免出现中文乱码
        return Base64.encodeBase64String(b);
 
    }
 
    /**
     * 解密
     * @param encryptStr 解密的字符串
     * @param decryptKey 解密的key值
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptStr, String decryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
        // 采用base64算法进行转码,避免出现中文乱码
        byte[] encryptBytes = Base64.decodeBase64(encryptStr);
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }
}